<script setup>
import { addCateApi, updateCateInfoApi } from '@/api'
import { ElMessage } from 'element-plus'
import { ref } from 'vue'

const dialogVisible = ref(false)
const form = ref({
  cate_name: '',
  cate_alias: ''
})
const rules = {
  cate_name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    {
      pattern: /^\S{1,10}$/,
      message: '分类名必须是1-10位的非空字符',
      trigger: 'blur'
    }
  ],
  cate_alias: [
    { required: true, message: '请输入分类别名', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9]{1,15}$/,
      message: '分类别名必须是1-15位的非空数字或字母',
      trigger: 'blur'
    }
  ]
}
const refForm = ref()
const emit = defineEmits(['success'])

const openEdit = (obj) => {
  dialogVisible.value = true
  console.log(obj)
  form.value = { ...obj }
}
const onCancel = async () => {
  form.value = ref({
    cate_name: '',
    cate_alias: ''
  })
  await refForm.value.resetFields()
  dialogVisible.value = false
}
const onSubmit = async () => {
  await refForm.value.validate()
  if (form.value.id) {
    await updateCateInfoApi(form.value)
    ElMessage.success('更新成功')
  } else {
    await addCateApi(form.value)
    ElMessage.success('添加成功')
  }
  emit('success')
  dialogVisible.value = false
}

defineExpose({
  openEdit
})
</script>
<template>
  <el-dialog
    v-model="dialogVisible"
    :title="form.id ? '编辑分类' : '添加分类'"
    width="30%"
    :before-close="onCancel"
  >
    <el-form
      ref="refForm"
      :model="form"
      :rules="rules"
      label-width="100px"
      style="padding-right: 30px"
    >
      <el-form-item label="分类名称" prop="cate_name">
        <el-input v-model="form.cate_name" />
      </el-form-item>
      <el-form-item label="分类别名" prop="cate_alias">
        <el-input v-model="form.cate_alias" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="onCancel">取消</el-button>
        <el-button type="primary" @click="onSubmit">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped></style>
